package com.yqy.controller;

import com.yqy.dao.EmployeeDao;
import com.yqy.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class EmployeeRESTController {
    @Autowired
    private EmployeeDao employeeDao;
    @GetMapping("/employee")
    public String getAllEmployees(Model model){
        //获取所有的员工信息
        Collection<Employee> employees = employeeDao.getAll();
        //把员工信息共享到请求域
        model.addAttribute("allEmployees",employees);
        return "employee_list";
    }

    @PostMapping("/employee")
    public String addEmploy(Employee employee){
        //保存员工信息
        employeeDao.save(employee);
        //重定向
        return "redirect:/employee";
    }

    @GetMapping("/to/update/{id}")
    public String toUpdate(@PathVariable("id") Integer id,Model model){
        //将员工信息回显到修改页面
        Employee employee = employeeDao.get(id);
        model.addAttribute("employee",employee);
        return "employee_update";
    }

    @PutMapping("/employee")
    public String updateEmployee(Employee employee){
        employeeDao.save(employee);
        return "redirect:/employee";
    }

    @GetMapping("/to/delete/{id}")
    public String toDelete(@PathVariable("id") Integer id,Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("employee",employee);
        return "employee_delete";
    }

    @DeleteMapping("/employee")
    public String deleteEmployee(Employee employee){
        employeeDao.delete(employee.getId());
        return "redirect:/employee";
    }
}
